import ButtonManager from './ButtonManager.js';

const ComplianceAppeal = {
  buttonId: 'complianceAppeal',
  defaultText: '8. 获取违规申诉列表',

  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this));
  },

  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '8. 获取申诉数据中...', true);
    ButtonManager.disableAllButtons(this.buttonId);

    try {
      // 从storage获取TEMU参数
      const { temu_antiContent, temu_mallId } = await new Promise(resolve => {
        chrome.storage.local.get(['temu_antiContent', 'temu_mallId'], resolve);
      });

      if (!temu_antiContent || !temu_mallId) {
        throw new Error('请先获取TEMU鉴权信息');
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: executeComplianceAppeal,
        args: [temu_mallId, temu_antiContent]
      });

      if (results?.[0]?.result) {
        console.log("违规申诉数据SPU获取完成:", results[0].result);
        
        chrome.storage.local.set({ appealdata: results[0].result }, function () {
          console.log("违规申诉数据SPU 已存储到 localStorage");
        });
      }
    } catch (error) {
      console.error("获取失败:", error);
      alert(error.message);
    } finally {
      ButtonManager.resetButtonState(this.buttonId, this.defaultText);
      ButtonManager.enableAllButtons();
    }
  }
};

// 执行逻辑（注入到页面）
function executeComplianceAppeal(j_mallid, j_anti_content) {
  return new Promise((resolve, reject) => {
    let j_total = 1;
    let j_pageNum = 1;
    let j_pagesNum = 1;
    let j_pageSize = 100;
    let j_spuIdsArr = [];
    
    function j_list() {
      const j_body = {
        page_num: j_pageNum,
        page_size: j_pageSize,
        target_type: "goods"
      };

      fetch("https://agentseller.temu.com/mms/tmod_punish/agent/merchant_appeal/entrance/list", {
        method: 'POST',
        headers: {
          'anti-content': j_anti_content,
          'mallid': j_mallid,
          'content-type': 'application/json'
        },
        body: JSON.stringify(j_body)
      })
      .then(response => {
        if (!response.ok) throw new Error('网络响应异常');
        return response.json();
      })
      .then(data => {
        if (data.success) {
          j_pagesNum = Math.ceil(data.result.total / j_pageSize);
          data.result.punish_appeal_entrance_list.forEach(item => {
            j_spuIdsArr.push(item.spu_id);
          });

          if (j_pageNum < j_pagesNum) {
            j_pageNum++;
            j_list();
          } else {
            // 分块处理结果
            const chunkedArr = [];
            for (let i = 0; i < j_spuIdsArr.length; i += 100) {
              chunkedArr.push(j_spuIdsArr.slice(i, i + 100));
            }
            resolve(chunkedArr);
          }
        } else {
          reject('接口返回失败');
        }
      })
      .catch(error => reject(error));
    }

    j_list();
  });
}

export default ComplianceAppeal;